﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using AsyncOAuth;
using System.Net.Http;
using System.Security.Cryptography;

namespace animexx.OAuth
{
    public partial class OAuthPage : PhoneApplicationPage
    {
        bool token_fetched = false;
        OAuthAuthorizer authorizer;
        RequestToken requestToken;

        public OAuthPage()
        {
            InitializeComponent();

            token_fetched = (App.accessToken != null);

            authorizer = new OAuthAuthorizer(Keys.ConsumerKey, Keys.ConsumerSecret);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            startAuthentication();
        }

        private async void startAuthentication()
        {
            var tokenResponse = await authorizer.GetRequestToken(Urls.BaseUrl + Urls.RequestTokenUrl);
            requestToken = tokenResponse.Token;

            var authorizeUrl = authorizer.BuildAuthorizeUrl(Urls.BaseUrl + Urls.AuthorizeUrl, requestToken);

            OAuthWebControl.Navigate(new Uri(authorizeUrl + "&oauth_callback=http://localhost", UriKind.Absolute));
        }

        private async void OAuthWebControl_Navigating(object sender, NavigatingEventArgs e)
        {
            if (e.Uri.Host == "localhost")
            {
                e.Cancel = true;

                string verifier = null;
                var parameters = QueryParameter.GetQueryParameters(e.Uri.Query);
                foreach (QueryParameter param in parameters) {
                    if (param.Name == "oauth_verifier")
                        verifier = param.Value;
                }

                var accessToken = await authorizer.GetAccessToken(Urls.BaseUrl + Urls.AccessTokenUrl, requestToken, verifier);
                if (accessToken.Token != null)
                {
                    App.accessToken = accessToken.Token;
                    NavigationService.GoBack();
                }
                else
                {
                    MessageBox.Show("Error fetching AccessToken.");
                    startAuthentication();
                }
//                var client = new HttpClient(new OAuthMessageHandler(Keys.ConsumerKey, Keys.ConsumerSecret, App.OAuthSettings.OAuthAccessToken));
//                var json = await client.GetStringAsync(Urls.BaseUrl + "json/mitglieder/ich");
//                System.Diagnostics.Debug.WriteLine("ich:" + json);

//                json = await client.GetStringAsync(Urls.BaseUrl + "json/kontakte/get_kontakte");
//                System.Diagnostics.Debug.WriteLine("kontakte:" + json);

//                json = await client.GetStringAsync(Urls.BaseUrl + "json/ens/ordner_liste");
//                System.Diagnostics.Debug.WriteLine("ens ordner:" + json);

//                json = await client.GetStringAsync(Urls.BaseUrl + "json/ens/ordner_ens_liste?ordner_id=1&ordner_typ=an");
//                System.Diagnostics.Debug.WriteLine("ens liste:" + json);

//                json = await client.GetStringAsync(Urls.BaseUrl + "json/persstart/list_widgets");
//                System.Diagnostics.Debug.WriteLine("ps widgets:" + json);

//                json = await client.GetStringAsync(Urls.BaseUrl + "json/persstart5/list_widgets");
//                System.Diagnostics.Debug.WriteLine("ps5 widgets:" + json);

//                json = await client.GetStringAsync(Urls.BaseUrl + "json/aidb/mangas/alle");
//                System.Diagnostics.Debug.WriteLine("mangas:" + json);

            }
        }

    }
}